package com.hwd.srb.core.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hwd.srb.common.exception.Assert;
import com.hwd.srb.common.result.ResponseEnum;
import com.hwd.srb.core.enmu.UserBindEnum;
import com.hwd.srb.core.hfb.FormHelper;
import com.hwd.srb.core.hfb.HfbConst;
import com.hwd.srb.core.hfb.RequestHelper;
import com.hwd.srb.core.mapper.UserBindMapper;
import com.hwd.srb.core.mapper.UserInfoMapper;
import com.hwd.srb.core.pojo.entity.UserBind;
import com.hwd.srb.core.pojo.entity.UserInfo;
import com.hwd.srb.core.pojo.vo.UserBindVO;
import com.hwd.srb.core.service.UserBindService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 用户绑定表 服务实现类
 * </p>
 *
 * @author 黄伟东/Victor
 * @since 2022-03-10
 */
@Service
public class UserBindServiceImpl extends ServiceImpl<UserBindMapper, UserBind> implements UserBindService {

    @Resource
    private UserInfoMapper userInfoMapper;

    /**
     * 账户绑定
     *
     * @param userBindVO 账户绑定对象
     * @param userId     账户id
     * @return java.lang.String
     */
    @Override
    public String bind(UserBindVO userBindVO, Long userId) {

        // 查询身份证号码是否绑定
        LambdaQueryWrapper<UserBind> queryWrapper = new LambdaQueryWrapper<UserBind>()
                .eq(UserBind::getIdCard, userBindVO.getIdCard())
                .ne(UserBind::getUserId, userId);
        UserBind userBind = baseMapper.selectOne(queryWrapper);
        Assert.isNull(userBind, ResponseEnum.USER_BIND_IDCARD_EXIST_ERROR);

        // 查询用户绑定信息,保存用户绑定信息，或修改用户信息（上一次未确认绑定）
        queryWrapper = new LambdaQueryWrapper<UserBind>()
                .eq(UserBind::getUserId, userId);
        userBind = baseMapper.selectOne(queryWrapper);

        if (userBind != null) {
            // 修改用户绑定信息
            BeanUtils.copyProperties(userBindVO, userBind);
            baseMapper.updateById(userBind);
        } else {
            // 保存用户绑定信息
            userBind = new UserBind();
            BeanUtils.copyProperties(userBindVO, userBind);
            userBind.setUserId(userId);
            userBind.setStatus(UserBindEnum.NO_BIND);
            baseMapper.insert(userBind);
        }

        // 调用汇付宝api生成表单
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("agentId", HfbConst.AGENT_ID);
        paramMap.put("agentUserId", userId);
        paramMap.put("idCard", userBindVO.getIdCard());
        paramMap.put("personalName", userBindVO.getName());
        paramMap.put("bankRType", userBindVO.getBankType());
        paramMap.put("bankNo", userBindVO.getBankNo());
        paramMap.put("mobile", userBindVO.getMobile());

        paramMap.put("returnUrl", HfbConst.USER_BIND_RETURN_URL);// 前端地址跳转页面
        paramMap.put("notifyUrl", HfbConst.USER_BIND_NOTIFY_URL);// 后端地址异步通知，修改绑定状态
        paramMap.put("timestamp", RequestHelper.getTimestamp());
        paramMap.put("sign", RequestHelper.getSign(paramMap));

        return FormHelper.buildForm(HfbConst.USER_BIND_URL, paramMap);
    }

    /**
     * 账户绑定异步回调，更新账户绑定状态
     *
     * @param paramMap 结果参数
     */
    @Override
    public void notifyBind(Map<String, Object> paramMap) {

        // 获取回调 参数
        String resultCode = (String) paramMap.get("resultCode");
        String bindCode = (String) paramMap.get("bindCode");
        String agentUserId = (String) paramMap.get("agentUserId");

        Assert.isTrue(resultCode.equals("0001"),ResponseEnum.WEIXIN_CALLBACK_PARAM_ERROR);

        // 更新user_bind表
        LambdaQueryWrapper<UserBind> queryWrapper = new LambdaQueryWrapper<UserBind>()
                .eq(UserBind::getUserId, agentUserId);
        UserBind userBind = baseMapper.selectOne(queryWrapper);
        userBind.setStatus(UserBindEnum.BIND_OK);
        userBind.setBindCode(bindCode);
        baseMapper.updateById(userBind);

        // 更新user_info表
        UserInfo userInfo = new UserInfo();
        userInfo.setId(userBind.getUserId());
        userInfo.setNickName(userBind.getName());
        userInfo.setName(userBind.getName());
        userInfo.setBindStatus(UserBindEnum.BIND_OK);
        userInfo.setIdCard(userBind.getIdCard());
        userInfo.setBindCode(bindCode);

        // 执行更新
        userInfoMapper.updateById(userInfo);
    }

    /**
     * 判定当前用户是有已经绑定账户
     *
     * @param userId 用户id
     * @return boolean
     */
    @Override
    public boolean hasBindById(String userId) {

        // 根据用户id数据库查询绑定状态
        LambdaQueryWrapper<UserInfo> queryWrapper = new LambdaQueryWrapper<UserInfo>()
                .select(UserInfo::getBindStatus)
                .eq(UserInfo::getId, userId);
        UserInfo userInfo = userInfoMapper.selectOne(queryWrapper);

        return userInfo.getBindStatus().equals(UserBindEnum.BIND_OK);
    }

    /**
     * 根据userId获取bindCode
     *
     * @param userId userId
     * @return java.lang.String
     */
    @Override
    public String getBindCodeByUserId(Long userId) {
        String bindCode = null;
        LambdaQueryWrapper<UserBind> queryWrapper = new LambdaQueryWrapper<UserBind>()
                .select(UserBind::getBindCode)
                .eq(UserBind::getUserId, userId);
        UserBind userBind = baseMapper.selectOne(queryWrapper);
        if (userBind != null) {
            bindCode = userBind.getBindCode();
        }
        return bindCode;
    }
}
